//
//  MySegmentView.m
//  Demo
//
//  Created by MacPro on 15/12/17.
//  Copyright © 2015年 pccb. All rights reserved.
//

#import "MySegmentView.h"

@interface MySegmentView ()

@property (strong, nonatomic) UILabel *bottonLabel;
@property (strong, nonatomic) UIButton *selectedBtn;

@end

@implementation MySegmentView

- (instancetype)initWithFrame:(CGRect)frame withTitle:(NSArray *)titleArray
{
    self = [super initWithFrame:frame];
    
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        NSInteger count = [titleArray count];
        
        //添加3个按钮
        for (int i = 0; i < count; i ++) {
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(self.width/3.0f*i, 0.0f, self.width/3.0f, self.height);
            [btn setTitle:titleArray[i] forState:UIControlStateNormal];
            [btn setTitleColor:HexRGB(0x808485) forState:UIControlStateNormal];
            [btn setTitleColor:DefaultColor_BlueButton forState:UIControlStateHighlighted];
            [btn setTitleColor:DefaultColor_BlueButton forState:UIControlStateSelected];
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
            [btn addTarget:self action:@selector(clickTitleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = 100 + i;
            [self addSubview:btn];
            
            if (i == 0) {
                _selectedBtn = btn;
                _selectedBtn.selected = YES;
            }
            
            if (i < count - 1) {
                //分割线
                UILabel *lineLab = [[UILabel alloc] initWithFrame:CGRectMake(self.width/3.0f * (i +1), self.height/4.0f, 1.0f, self.height/2.0f)];
                lineLab.backgroundColor = HexRGB(0xf1f1f1);
                [self addSubview:lineLab];
            }
            
        }
        
        
        _bottonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.height - 1.0f, self.width / 3.0f, 1.0f)];
        _bottonLabel.backgroundColor = DefaultColor_BlueButton;
        [self addSubview:_bottonLabel];
        
    }
    
    return self;
}

- (void)clickTitleBtnClick:(UIButton *)sender
{
    _selectedBtn.selected = NO;
    sender.selected = YES;
    _selectedBtn = sender;
    
    CGRect labelFrame = _bottonLabel.frame;
    labelFrame.origin.x = sender.left;
    
    [UIView animateWithDuration:0.5f animations:^{
        _bottonLabel.frame = labelFrame;
    }];
    
    if (self.clickSegmentViewBlock) {
        self.clickSegmentViewBlock(sender.tag);
    }
}

@end
